package todo_app

import (
	"fmt"
	"sync/atomic"
)

type tTodoWriter struct {
	id string
}

func newTodoWriter() iTodoWriter {
	it := new(tTodoWriter)
	it.init()
	return it
}

func (me *tTodoWriter) init() {
	me.id = fmt.Sprintf("tTodoWriter.%d", atomic.AddInt32(&gWriterCounter, 1))

	GlobalEventBus.Sub(EventWriteTodoCmd, me.id, me.handleWriteTodoCmd)
}

func (me *tTodoWriter) handleWriteTodoCmd(e string, args interface{}) {
	switch e {
	case EventWriteTodoCmd:
		if it, ok := args.(*TodoEvent); ok {
			me.HandleTodoEvent(it)
		}
		break
	}
}

func (me *tTodoWriter) HandleTodoEvent(e *TodoEvent) {
	j := gDefaultEventSerializer.Serialize(e)
	if j != nil {
		MockJSONStore.Append(j)
	}
}

var gWriterCounter int32 = 0
